/* eslint-disable prefer-destructuring */
/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable react/jsx-no-bind */
/* eslint-disable react/sort-comp */
import React, { PureComponent, createRef } from 'react';
import { connect } from 'dva';
import { Form, Input, Button, Select, Popconfirm, Row, Col } from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import InfoCheck from '@/components/InfoCheck';
import { debounce } from 'lodash';
import styles from './style.less';
import { Add, Role } from './_components/Accounts';
import { ZyAdd, Roles } from './_components/ZY_add_roles';
import AddressTree from './_components/AddressTree';
import DispatchZone from './_components/DispatchZone';
import { districtIds } from './_components/utils';

const { Option } = Select;
const FormItem = Form.Item;

@connect(({ accounts, loading, user, setting }) => ({
  tableData: accounts.data,
  zySelectedBranch: accounts.zySelectedArray,
  userInfo: user.currentUser.user_info,
  deleting: loading.effects['accounts/delete'],
  switching: loading.effects['accounts/switch'],
  getting: loading.effects['accounts/getAccounts'],
  zyLoading: loading.effects['accounts/zyGetAcountsList'],
  zySwitching: loading.effects['accounts/zySwitchStatus'],
  infoLoading: loading.effects['info/getInfo'],
  isZyAccount: setting.options.key === 'post' || setting.options.key === 'yjy', // 中邮和驿加易展示逻辑相同
}))
@Form.create()
class Accounts extends PureComponent {
  // 搜索
  handleSearch = debounce(
    e => {
      e.preventDefault();
      const { zySelectedBranch, isZyAccount } = this.props;
      const { length } = zySelectedBranch;
      isZyAccount
        ? this.getList(1, zySelectedBranch.slice(length - 1, length)[0].id)
        : this.getList(1);
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  handleTableChange = debounce(
    pagination => {
      const { zySelectedBranch, isZyAccount } = this.props;
      const { current } = pagination;
      const { length } = zySelectedBranch;
      isZyAccount
        ? this.getList(1, zySelectedBranch.slice(length - 1, length)[0].id)
        : this.getList(current);
      this.setState({ page: current });
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  constructor(props) {
    super(props);
    this.state = {
      selectedRows: [],
      isInfoReady: false,
      page: 1,
    };
    this.currentSwitchId = -1;
    this.status = [
      {
        key: '*',
        label: '全部',
      },
      {
        key: '1',
        label: '已关闭',
      },
      {
        key: '0',
        label: '已开启',
      },
    ];
    const { auths } = Role;
    this.columns = [
      {
        title: '登录手机号',
        dataIndex: 'phone',
        key: 'phone',
        width: '15%',
      },
      {
        title: '账户名',
        dataIndex: 'name',
        key: 'name',
        width: '10%',
      },
      {
        title: '已分配角色',
        dataIndex: 'privilege',
        key: 'privilege',
        width: '20%',
        render: value => {
          let valueArr = [];
          if (value) {
            valueArr = value.split(',');
          }
          const roles = valueArr.length === 0 ? ['alls'] : valueArr[0] == '*' ? ['alls'] : valueArr;

          return valueArr.length === 0
            ? ''
            : `${roles
                .map(item => {
                  const currentData = auths.filter(iitem => iitem.key === item)[0];
                  return currentData ? currentData.name : '';
                })
                .filter(item => !!item)
                .join('、')}管理员`;
        },
      },
      {
        title: '管理范围',
        dataIndex: 'area_name',
        width: '10%',
      },
      {
        title: '当前状态',
        dataIndex: 'is_forbiden',
        key: 'is_forbiden',
        width: '10%',
        render: value => this.status.filter(item => item.key == value)[0].label,
      },
      {
        title: '操作',
        dataIndex: 'is_forbiden',
        key: 'operator',
        width: '50%',
        render: (value, record) => {
          const { id, privilege } = record;
          const { deleting, switching } = this.props;
          const { page } = this.state;
          return (
            <div className={styles.operator}>
              <Button
                loading={switching && id === this.currentSwitchId}
                size="small"
                type="primary"
                onClick={this.handleSwitchStatus.bind(this, value, [id])}
              >
                {value == 1 ? '开启' : '禁用'}
                账号
              </Button>
              <Role ids={[id]} checked={privilege}>
                <Button size="small" type="primary">
                  角色分配
                </Button>
              </Role>
              <DispatchZone record={record} getList={this.getList.bind(this, page)}>
                <Button size="small" type="primary">
                  管理范围
                </Button>
              </DispatchZone>
              <Add data={record}>
                <Button size="small" type="primary">
                  修改账号
                </Button>
              </Add>
              <Popconfirm
                title="删除不可恢复，确定要删除吗？"
                onConfirm={this.handelDelete.bind(this, id)}
              >
                <Button
                  size="small"
                  type="primary"
                  loading={deleting && id === this.currentDeleteId}
                >
                  删除
                </Button>
              </Popconfirm>
            </div>
          );
        },
      },
    ];
    this.zyColumns = [
      {
        title: '账号',
        dataIndex: 'phone',
        key: 'phone',
        width: '20%',
        align: 'center',
      },
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
        align: 'center',
      },
      {
        title: '当前状态',
        dataIndex: 'status_desc',
        key: 'status',
        align: 'center',
      },
      {
        title: '操作',
        width: '324px',
        align: 'center',
        render: (text, record) => {
          const { uid, status, super: isSuper, branch_id, privilege, branch_level } = record;
          const { zySwitching, userInfo = {} } = this.props;
          const { page } = this.state;
          // 总公司超级管理员、当前账号不显示操作
          if (isSuper == 1 || (userInfo && userInfo.shop_id == uid)) return null;
          return (
            <div className={styles.operator}>
              <Popconfirm
                title={`确定${status != 1 ? '开启' : '禁用'}此账号？`}
                onConfirm={this.zySwitch.bind(this, status, uid, branch_id)}
              >
                <Button
                  loading={zySwitching && uid === this.currentSwitchId}
                  size="small"
                  type="primary"
                >
                  {status != 1 ? '开启' : '禁用'}
                  账号
                </Button>
              </Popconfirm>
              <ZyAdd
                data={{ ...record, title: 'modify' }}
                getListAfterAdded={this.handleAdded.bind(this, page, branch_id)}
              >
                <Button size="small" type="primary">
                  编辑
                </Button>
              </ZyAdd>
              <Popconfirm
                title="删除不可恢复，确定要删除吗？"
                onConfirm={this.zySwitch.bind(this, 0, uid, branch_id)}
              >
                <Button size="small" type="primary">
                  删除
                </Button>
              </Popconfirm>
              <Roles
                branchLevel={branch_level}
                uid={uid}
                privilege={privilege}
                getListAfterAdded={this.handleAdded.bind(this, page, branch_id)}
              >
                <Button size="small" type="primary">
                  权限分配
                </Button>
              </Roles>
            </div>
          );
        },
      },
    ];
    this.addressTreeRef = createRef();
  }

  getList(page, branchId) {
    const {
      dispatch,
      form: { getFieldsValue },
      userInfo,
      isZyAccount,
    } = this.props;
    const data = getFieldsValue();
    const { branchId: branch_id } = userInfo;
    const zyStatus = data.is_forbiden == '*' ? 'all' : data.is_forbiden == '1' ? '2' : '1';
    isZyAccount
      ? dispatch({
          type: 'accounts/zyGetAcountsList',
          payload: {
            branch_id: branchId || branch_id,
            status: zyStatus,
            phone: data.search,
            page,
            pageSize: 20,
          },
        })
      : dispatch({
          type: 'accounts/getList',
          payload: {
            ...data,
          },
        });
    this.setState({ page });
  }

  handleInfoReady() {
    // if (!data.name) return;  //中邮账号暂时绕过
    const { page } = this.state;
    this.setState({ isInfoReady: true });
    this.getList(page);
  }

  // 新增账号
  handleAdded(page, branchId) {
    this.getList(page, branchId);
  }

  // 删除
  handelDelete(ids) {
    const { dispatch } = this.props;
    this.currentDeleteId = ids;
    dispatch({
      type: 'accounts/delete',
      payload: {
        id: ids,
      },
      then: () => {
        this.getList();
      },
    });
  }

  // 清除选中项目
  clearSelectRows() {
    this.setState({
      selectedRows: [],
    });
  }

  // 中邮，删除/开启/禁用
  zySwitch(status, uid, branch_id) {
    const { dispatch } = this.props;
    const { page } = this.state;
    this.currentSwitchId = uid;
    dispatch({
      type: 'accounts/zySwitchStatus',
      payload: {
        status: status == 1 ? 2 : status == 2 ? 1 : 0,
        uid,
      },
    }).then(() => {
      this.getList(page, branch_id);
    });
  }

  // 开启/关闭
  handleSwitchStatus(is_forbiden, ids) {
    const { dispatch } = this.props;
    if (!ids) {
      const { selectedRows } = this.state;
      const list = [];
      selectedRows.forEach(item => {
        if (item.is_forbiden == is_forbiden) {
          list.push(item.id);
        }
      });
      ids = list;
      this.currentSwitchId = -1 - is_forbiden;
    } else {
      this.currentSwitchId = ids[0];
    }

    dispatch({
      type: 'accounts/switch',
      payload: {
        id: ids,
        is_forbiden: is_forbiden == 0 ? 1 : 0,
      },
      then: this.clearSelectRows.bind(this),
    });
  }

  handleSelectRow(selectedRows) {
    this.setState({
      selectedRows,
    });
  }

  /**
   * 控制是否显示支局修改按钮
   *  */
  selectedZj = () => {
    const { zySelectedBranch } = this.props;
    const { level, pid: _pid } = zySelectedBranch.find(v => v.isLeaf) || {};
    return districtIds.includes(`${_pid}`) && level == 4;
  };

  updateZJTreeList = id => {
    this.addressTreeRef.current.updateZJTreeList(id);
  };

  render() {
    const {
      form: { getFieldDecorator },
      tableData,
      switching,
      getting,
      userInfo = {},
      zyLoading,
      infoLoading,
      isZyAccount,
      zySelectedBranch,
    } = this.props;
    const { selectedRows, isInfoReady } = this.state;
    const { branchId: companyId } = userInfo;
    const ids = selectedRows.map(item => item.id);
    const loading = getting || infoLoading || zyLoading;

    return (
      <PageHeaderLayout title="账号管理">
        <InfoCheck onReady={this.handleInfoReady.bind(this)} />
        <Row type="flex" gutter={16}>
          {isZyAccount && (
            <Col md={4} sm={24} xs={24}>
              <AddressTree
                ref={this.addressTreeRef}
                getListAfterAdded
                isInfoReady={isInfoReady}
                userInfo={userInfo}
              />
            </Col>
          )}
          <Col md={isZyAccount ? 20 : 24} sm={24} xs={24}>
            <div className={styles.main}>
              <Form hideRequiredMark className={styles['search-form']} layout="inline">
                <FormItem label="账号状态">
                  {getFieldDecorator('is_forbiden', {
                    initialValue: '*',
                  })(
                    <Select style={{ width: 100 }}>
                      {this.status.map(item => (
                        <Option key={item.key}>{item.label}</Option>
                      ))}
                    </Select>,
                  )}
                </FormItem>
                <FormItem label="手机号或账户名" help="">
                  {getFieldDecorator('search', {
                    initialValue: '',
                  })(
                    <Input
                      style={{ width: 200 }}
                      maxLength={20}
                      placeholder="请输入手机号或账户名"
                    />,
                  )}
                </FormItem>
                <FormItem>
                  <Button
                    type="primary"
                    icon="search"
                    loading={loading}
                    onClick={this.handleSearch}
                  >
                    查询
                  </Button>
                </FormItem>
                <FormItem>
                  {isZyAccount ? (
                    <ZyAdd getListAfterAdded={this.handleAdded.bind(this)} data={{ title: 'add' }}>
                      <Button ghost type="primary" icon="plus" loading={loading} disabled={loading}>
                        添加账号
                      </Button>
                    </ZyAdd>
                  ) : (
                    <Add onAdded={this.handleAdded.bind(this)}>
                      <Button ghost type="primary" icon="plus" loading={loading} disabled={loading}>
                        新增账号
                      </Button>
                    </Add>
                  )}
                </FormItem>
                {isZyAccount &&
                  this.selectedZj() && (
                    <FormItem>
                      <ZyAdd
                        updateZJTreeList={this.updateZJTreeList}
                        data={{ title: 'zj_edit', companyId, branch: zySelectedBranch }}
                      >
                        <Button
                          ghost
                          type="primary"
                          icon="edit"
                          loading={loading}
                          disabled={loading}
                        >
                          修改支局
                        </Button>
                      </ZyAdd>
                    </FormItem>
                  )}
              </Form>
              {isZyAccount ? (
                <StandardTable
                  rowKey={({ uid }) => uid}
                  loading={zyLoading}
                  data={tableData}
                  columns={this.zyColumns}
                  onSelectRow={this.handleSelectRow.bind(this)}
                  onChange={this.handleTableChange}
                />
              ) : (
                <>
                  <StandardTable
                    rowKey="id"
                    loading={getting}
                    selectedRows={selectedRows}
                    data={tableData}
                    columns={this.columns}
                    onSelectRow={this.handleSelectRow.bind(this)}
                  />
                  <div className={styles.batchButton}>
                    <Button
                      loading={switching && this.currentSwitchId === -1}
                      disabled={!selectedRows.length}
                      type="primary"
                      onClick={this.handleSwitchStatus.bind(this, 1, null)}
                    >
                      批量开启
                    </Button>
                    <Button
                      loading={switching && this.currentSwitchId === -2}
                      disabled={!selectedRows.length}
                      type="primary"
                      onClick={this.handleSwitchStatus.bind(this, 0, null)}
                    >
                      批量禁用
                    </Button>
                    <Role ids={ids} onAssigned={this.clearSelectRows.bind(this)}>
                      <Button disabled={!selectedRows.length} type="primary">
                        批量分配角色
                      </Button>
                    </Role>
                  </div>
                </>
              )}
            </div>
          </Col>
        </Row>
      </PageHeaderLayout>
    );
  }
}

export default Accounts;
